package com.hitqz.robot.biz.config;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
 * EasyExcel 指定列合并相同值的行的单元格 处理器
 */
@AllArgsConstructor
@Slf4j
public class MultiColumnMergeHandler implements CellWriteHandler {
    private final List<Integer> mergeColumnIndexes; // 需要合并的列索引
    private int headerRowCount = -1; // 动态记录表头行数
    private final int dataRowCount; // 动态记录数据行数
    private int headerColumnIndex = -1;

    /**
     * 构造函数，传入需要合并的列索引列表
     * @param dataRowCount 数据行数量list.size()
     * @param mergeColumnIndexes 需要合并的列索引列表,从0开始
     */
    public MultiColumnMergeHandler(Integer dataRowCount,List<Integer> mergeColumnIndexes) {
        this.dataRowCount = dataRowCount;
        this.mergeColumnIndexes = mergeColumnIndexes;
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        if (Boolean.TRUE.equals(isHead)) {
            headerColumnIndex = head.getColumnIndex() > headerColumnIndex ? head.getColumnIndex() : headerColumnIndex;
            return; // 跳过表头
        }
        // 记录表头
        if (headerRowCount == -1){
            headerRowCount = cell.getRowIndex();
        }

        // 仅在数据写入完成后合并
        int currentRowCount = sheet.getLastRowNum()+1;
        if (dataRowCount == currentRowCount - headerRowCount && cell.getColumnIndex() == headerColumnIndex) {
            for (Integer columnIndex : mergeColumnIndexes) {
                try {
                    mergeColumn(sheet, columnIndex);
                    log.info("合并单元格列:{}", columnIndex);
                }catch (Exception e){
                    log.info("合并单元格列失败:{}",columnIndex);
                }
            }
            log.info("合并单元格完成");
        }
    }

    /**
     * 按列合并相同内容的单元格（跳过表头）
     */
    private void mergeColumn(Sheet sheet, int columnIndex) {
        int startRow = headerRowCount; // 数据起始行
        int endRow = headerRowCount;
        String prevValue = getCellValue(sheet, startRow, columnIndex);

        for (int i = headerRowCount; i < sheet.getLastRowNum(); i++) {
            String currentValue = getCellValue(sheet, i, columnIndex);
            if (currentValue.equals(prevValue)) {
                endRow++;
            } else {
                if (endRow > startRow) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, columnIndex, columnIndex));
                }
                startRow = i+1;
                endRow = i+1;
                prevValue = currentValue;
            }
        }

        // 处理最后一组
        if (endRow > startRow) {
            sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, columnIndex, columnIndex));
        }
    }

    /**
     * 获取单元格的字符串值
     */
    private String getCellValue(Sheet sheet, int rowIndex, int columnIndex) {
        if (sheet.getRow(rowIndex) != null && sheet.getRow(rowIndex).getCell(columnIndex) != null) {
            Cell cell = sheet.getRow(rowIndex).getCell(columnIndex);
            DataFormatter dataFormatter = new DataFormatter();
            return dataFormatter.formatCellValue(cell).trim();
        }
        return "";
    }


}
